package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyContent;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyCommendService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.IStrategyTagService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.impl.impl.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.query.StrategyCommentQueryObject;
import cn.wolfcode.luowowo.common.query.StrategyQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 攻略的控制器
 */

@Controller
@RequestMapping("/strategy")
public class StrategyController {

    @Reference
    private IStrategyTagService strategyTagService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    //评论
    @Reference
    private IStrategyCommentService strategyCommentService;

    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;

    //推荐
    @Reference
    private IStrategyCommendService strategyCommendService;

    @Reference
    private IStrategySearchService strategySearchService;


    @RequestMapping("")
    public Object index(Model model) {

        //commends 推荐攻略
        model.addAttribute("commends", strategyCommendService.listTop5());

        //upCds 攻略飙升排行榜(阅读数+评论数的和的降序)
        model.addAttribute("upCds", strategyStatsCacheService.listRankTop10(RedisKey.STRATEGY_STATS_UP_SORT));

        // hotCds 攻略热门排行榜(收藏数+点赞数的和的降序)
        model.addAttribute("hotCds", strategyStatsCacheService.listRankTop10(RedisKey.STRATEGY_STATS_HOT_SORT));

        //构建高级查询条件
        //unabroads 国内的省份数据
        model.addAttribute("unabroads", strategySearchService.listCondition(SearchQueryObject.CONDITION_UNABROAD));

        //abroads 海外的国家数据
        model.addAttribute("abroads",strategySearchService.listCondition(SearchQueryObject.CONDITION_ABROAD));

        //themes 主题数据
        model.addAttribute("themes",strategySearchService.listCondition(SearchQueryObject.CONDITION_THEME));

        //themeCds 主题推荐
        model.addAttribute("themeCds",strategySearchService.themeCommend());

        return "strategy/index";
    }

    /**
     * 攻略的列表
     *
     * @param qo
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public Object list(@ModelAttribute("qo") StrategyQueryObject qo, Model model) {

        List<Destination> toasts = destinationService.listToast(qo.getDestId());
        //土司
        model.addAttribute("toasts", toasts);

        //目的地 dest
        //model.addAttribute("dest", destinationService.get(qo.getDestId()));
        model.addAttribute("dest", toasts.remove(toasts.size() - 1));

        //标签 tags
        model.addAttribute("tags", strategyTagService.listByDestId(qo.getDestId()));

        //分页对象 pageInfo
        model.addAttribute("pageInfo", strategyDetailService.query(qo));
        return "/strategy/list";
    }

    @RequestMapping("/detail")
    public Object detail(Long id, Model model, @LoginUser UserInfo userInfo) {
        //detail 攻略文章
        StrategyDetail detail = strategyDetailService.get(id);
        StrategyContent content = strategyDetailService.getContent(id);
        detail.setStrategyContent(content);
        model.addAttribute("detail", detail);

        //vo 当前文章的数据统计对象
        model.addAttribute("vo", strategyStatsCacheService.getStats(id));

        //阅读量+1
        strategyStatsCacheService.incr(id, 1, IStrategyStatsCacheService.VIEWNUM_TYPE);

        //isFavor收藏量的回显(用户的id和文章的id)
        boolean favor = userInfo != null ? strategyStatsCacheService.isFavor(userInfo.getId(), id) : false;
        model.addAttribute("isFavor", favor);

        //攻略飙升排行榜+1
        strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT, 1, id);

        return "strategy/detail";
    }

    /**
     * 攻略评论
     * 资源：/strategy/commentAdd
     * 参数：
     * detailId=xx
     * content=xx
     * detailTitle=xx
     * 返回：
     * { success: true }
     *
     * @return
     */
    @RequiredLogin
    @ResponseBody
    @RequestMapping("/commentAdd")
    public Object commentAdd(StrategyComment entity, @LoginUser UserInfo user) {
        AjaxResult result = new AjaxResult();
        Long detailId = entity.getDetailId();

        //填充当前登录用户的信息
        entity.setHeadUrl(user.getHeadImgUrl());
        entity.setUserId(user.getId());
        entity.setUsername(user.getNickname());
        entity.setLevel(user.getLevel());
        //保存数据
        strategyCommentService.save(entity);

        //评论数
        strategyStatsCacheService.incr(detailId, 1, IStrategyStatsCacheService.REPLYNUM_TYPE);

        //查询但前评论数
        StrategyStats stats = strategyStatsCacheService.getStats(detailId);

        //攻略飙升排行榜+1             规则:阅读数+评论数
        strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT, 1, detailId);

        //返回评论数据
        return result.addData(stats.getReplynum());

    }

    /**
     * 查询所有的评论并进行分页
     *
     * @param qo
     * @param model
     * @return
     */
    @RequestMapping("/comment")
    public Object comment(StrategyCommentQueryObject qo, Model model) {
        model.addAttribute("page", strategyCommentService.query(qo));
        return "strategy/commentTpl";
    }

    /**
     * 点赞数的操作
     * 资源：/strategy/commentThumbUp
     * 参数：
     * toId=xx      当前评论的作者
     * fromId=xx    点赞的人的id
     * 返回：
     * { success: true }
     *
     * @return
     */
    @RequiredLogin
    @RequestMapping("/commentThumbUp")
    @ResponseBody
    public Object commentThumbUp(String toId, Long fromId) {
        AjaxResult result = new AjaxResult();
        try {
            strategyCommentService.commentThumbUp(toId, fromId);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("操作失败");
        }
        return result;
    }

    /**
     * 收藏数的统计操作
     *
     * @param strategyId
     * @return
     */
    @RequiredLogin
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long strategyId, @LoginUser UserInfo userInfo) {
        AjaxResult result = new AjaxResult();
        boolean success = strategyStatsCacheService.favor(userInfo.getId(), strategyId);
        //设置收藏结果
        result.setSuccess(success);
        //最后返回收藏数
        StrategyStats stats = strategyStatsCacheService.getStats(strategyId);

        //热门排行榜值+1
        int num = success ? 1 : -1;
        strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT, num, strategyId);

        return result.addData(stats.getFavornum());
    }

    /**
     * 点赞数的统计操作
     *
     * @param strategyId
     * @param userInfo
     * @return
     */
    @RequiredLogin
    @RequestMapping("/strategyThumbup")
    @ResponseBody
    public Object strategyThumbup(Long strategyId, @LoginUser UserInfo userInfo) {
        AjaxResult result = new AjaxResult();
        boolean success = strategyStatsCacheService.strategyThumbup(userInfo.getId(), strategyId);
        result.setSuccess(success);
        //查询出收藏数,然后返回
        StrategyStats stats = strategyStatsCacheService.getStats(strategyId);

        //热门排行榜值+1
        if (success) {
            strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT, 1, strategyId);
        }
        return result.addData(stats.getThumbsupnum());
    }

    //http://localhost/strategy/searchPage
    @RequestMapping("/searchPage")
    public Object searchPage(SearchQueryObject qo,Model model){
        model.addAttribute("page",strategySearchService.query(qo));
        return "strategy/searchPageTpl";
    }

}
